﻿using Sc.Domain;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Persistence
{
    public class SendCarRecordDAO
    {
        /// <summary>
        /// 待办事宜
        /// </summary>
        private readonly Sys_ToDoListDAO dao = new Sys_ToDoListDAO();
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="list">业务数据</param>
        /// <returns></returns>
        public int SaveData(IList<SendCarRecord> list)
        {
            IList<HelperModel> sqls = new List<HelperModel>();
            foreach (var item in list)
            {
                HelperModel ent = new HelperModel();
                StringBuilder strSql = new StringBuilder();
                strSql.Append("insert into SendCarRecord(");
                strSql.Append("CarUseNo,Driver,CarNo,IsBack,BackTime,ScUserId)");
                strSql.Append(" values (");
                strSql.Append("@CarUseNo,@Driver,@CarNo,@IsBack,@BackTime,@ScUserId)");
                ent.Sql = strSql.ToString();
                SqlParameter[] parameters = {
                    new SqlParameter("@CarUseNo", SqlDbType.Int),
                    new SqlParameter("@Driver", SqlDbType.Int),
                    new SqlParameter("@CarNo", SqlDbType.Int),
                    new SqlParameter("@IsBack", SqlDbType.Bit),
                    new SqlParameter("@BackTime", SqlDbType.DateTime),
                    new SqlParameter("@ScUserId", SqlDbType.Int)};
                parameters[0].Value = item.CarUseNo;
                parameters[1].Value = item.Driver;
                parameters[2].Value = item.CarNo;
                parameters[3].Value = item.IsBack;
                parameters[4].Value = DateTime.Now;
                parameters[5].Value = item.ScUserId;
                ent.Parameter = parameters;
                sqls.Add(ent);
                //--------------------------更新车辆状态为已派出--------------------//
                HelperModel carInfo = new HelperModel();
                carInfo.Sql = "UPDATE CarInfo SET CarState=1 WHERE Id=@Id";
                carInfo.Parameter = new SqlParameter[] {
                     new SqlParameter("@Id", SqlDbType.Int)
                };
                carInfo.Parameter[0].Value = item.CarNo;
                sqls.Add(carInfo);
                //--------------------------更新用车申请状态为已派车----------------//
                HelperModel use = new HelperModel();
                use.Sql = "UPDATE Car_UseCarApplication SET InstanceState=4 WHERE Id=@Id";
                use.Parameter = new SqlParameter[] {
                     new SqlParameter("@Id", SqlDbType.Int)
                };
                use.Parameter[0].Value = item.CarUseNo;
                sqls.Add(use);
            }
            //---------------------------给司机发送待办------------------------//
            var u = list.GroupBy(it => it.Driver).ToList();
            for (int i = 0; i < u.Count; i++)
            {
                Sys_ToDoList lt = new Sys_ToDoList()
                {
                    ActionURL = string.Empty,
                    CreaterName = "系统",
                    Name = "您的车已派出，请查看",
                    Source = "DRVE" + u[i].Key,
                    State = 0,
                    UrgencyDegree = 0,
                    UserId = u[i].Key
                };
                sqls.Add(dao.AddToDo(lt));
            }
            //---------------------------给申请发送待办------------------------//
            var dl = list.GroupBy(it => it.CarUseNo).ToList();
            for (int i = 0; i < dl.Count; i++)
            {
                Sys_ToDoList lt = new Sys_ToDoList()
                {
                    ActionURL = string.Empty,
                    CreaterName = "系统",
                    Name = "您的用车申请已派车，请查看",
                    Source = "DRVE" + dl[i].Key,
                    State = 0,
                    UrgencyDegree = 0,
                    UserId = dl[i].First().ApplicationId
                };
                sqls.Add(dao.AddToDo(lt));
            }
            return DbHelperSQL.ExecuteSqlTran(sqls);
        }
        /// <summary>
        /// 获取当前司机可还车
        /// </summary>
        /// <param name="userId">司机ID</param>
        /// <returns></returns>
        public IList<SendCarTemp> GetSendCarRecord(int userId)
        {
            IList<SendCarTemp> list = new List<SendCarTemp>();
            string sql = "SELECT * FROM VW_CarRecord WHERE Driver=@Driver AND IsBack=@IsBack";
            SqlParameter[] param = new SqlParameter[]{
                new SqlParameter("@Driver",SqlDbType.Int),
                new SqlParameter("@IsBack",SqlDbType.Bit)
            };
            param[0].Value = userId;
            param[1].Value = false;
            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sql, param))
            {
                while (sdr.Read())
                {
                    list.Add(BuildObjectFromIDataReader(sdr));
                }
                sdr.Close();
            }
            return list;
        }

        /// <summary>
        /// 获取当前车辆的可还车
        /// </summary>
        /// <param name="carNo">车牌号</param>
        /// <returns></returns>
        public IList<SendCarTemp> GetSendCarRecordByCar(string carNo)
        {
            IList<SendCarTemp> list = new List<SendCarTemp>();
            string sql = "SELECT * FROM VW_CarRecord WHERE CarNo=@carNo AND IsBack=@IsBack";
            SqlParameter[] param = new SqlParameter[]{
                new SqlParameter("@carNo",SqlDbType.NVarChar,50),
                new SqlParameter("@IsBack",SqlDbType.Bit)
            };
            param[0].Value = carNo;
            param[1].Value = false;
            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sql, param))
            {
                while (sdr.Read())
                {
                    list.Add(BuildObjectFromIDataReader(sdr));
                }
                sdr.Close();
            }
            return list;
        }

        /// <summary>
        /// 获取单条派车记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Car_UseCarApplication GetCar_UseCarApplication(int id)
        {
            Car_UseCarApplication result = null;
            string sql = "SELECT * FROM VW_CarRecord WHERE Id=@Id";
            SqlParameter parm = new SqlParameter("@Id", SqlDbType.Int, 4);
            parm.Value = id;

            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sql, parm))
            {
                if (sdr.Read())
                {
                    result = new Car_UseCarApplication();
                    result = BuildCar_UseCarApplicationFromIDataReader(sdr);
                }
                sdr.Close();
            }
            return result;
        }

        public Car_UseCarApplication Ge_SendtCarPrint(int id)
        {
            Car_UseCarApplication result = null;
            string sql = "SELECT * FROM VW_SendCarPrint WHERE Id=@Id";
            SqlParameter parm = new SqlParameter("@Id", SqlDbType.Int, 4);
            parm.Value = id;

            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sql, parm))
            {
                if (sdr.Read())
                {
                    result = new Car_UseCarApplication();
                    result = BuildCar_UseCarApplicationFromIDataReaderPrint(sdr);
                }
                sdr.Close();
            }
            return result;

        }

        private Car_UseCarApplication BuildCar_UseCarApplicationFromIDataReaderPrint(SqlDataReader dr)
        {
            try
            {
                Car_UseCarApplication obj = new Car_UseCarApplication();
                obj.Id = (dr["Id"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("Id")));
                obj.StartAddress = (dr["StartAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("StartAddress")));
                obj.EndAddress = (dr["EndAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("EndAddress")));
                obj.StartTime = (dr["StartTime"] == System.DBNull.Value ? new DateTime(1900, 1, 1) : dr.GetDateTime(dr.GetOrdinal("StartTime")));
                obj.TotalCount = (dr["TotalCount"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("TotalCount")));
                obj.Remark = (dr["Remark"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("Remark")));
                obj.InstanceState = (dr["InstanceState"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("InstanceState")));
                if (dr["IsComplaint"] != null && dr["IsComplaint"].ToString() != "")
                {
                    if ((dr["IsComplaint"].ToString() == "1") || (dr["IsComplaint"].ToString().ToLower() == "true"))
                    {
                        obj.IsComplaint = true;
                    }
                    else
                    {
                        obj.IsComplaint = false;
                    }
                }
                if (dr["BussinessState"] != null && dr["BussinessState"].ToString() != "")
                {
                    if ((dr["BussinessState"].ToString() == "1") || (dr["BussinessState"].ToString().ToLower() == "true"))
                    {
                        obj.BussinessState = true;
                    }
                    else
                    {
                        obj.BussinessState = false;
                    }
                }
                obj.ComplaintState = (dr["IsComplaint"] == System.DBNull.Value ? 0 : Convert.ToInt32(dr["IsComplaint"]));
                //obj.ApproalUsers = (dr["ApproalUsers"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("ApproalUsers")));
                //obj.NodeCount = (dr["NodeCount"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("NodeCount")));
                obj.UserId = (dr["UserId"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("UserId")));
                obj.DriverName = (dr["DriverName"] == System.DBNull.Value ? String.Empty : dr["DriverName"].ToString());
                obj.CarNo = (dr["CarNo"] == System.DBNull.Value ? String.Empty : dr["CarNo"].ToString()) + "(" + (dr["CarTypeName"] == System.DBNull.Value ? String.Empty : dr["CarTypeName"].ToString()) + ")";
                obj.Orgz = (dr["DeptName"] == System.DBNull.Value ? String.Empty : dr["OrgzName"].ToString() + "/" + dr["DeptName"].ToString());
                obj.OrgzNo = (dr["OrgzNo"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("OrgzNo")));
                obj.UserName = (dr["UserName"] == System.DBNull.Value ? String.Empty : dr["UserName"].ToString());
                //obj.ExDate = (dr["ExDate"] == System.DBNull.Value ? new DateTime(1900, 1, 1) : dr.GetDateTime(dr.GetOrdinal("ExDate")));
                obj.Reson = (dr["Reson"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("Reson")));
                //obj.ZcTonnage = (dr["ZcTonnage"] == System.DBNull.Value ? 0M : dr.GetDecimal(dr.GetOrdinal("ZcTonnage")));
                return obj;
            }
            catch (Exception ex)
            {
                throw new Exception("从DataReader中读取数据失败，可能与相关的字段不存在有关！请检查！||" + ex.Message + "||" + ex.Source);
            }
        }

        private Car_UseCarApplication BuildCar_UseCarApplicationFromIDataReader(SqlDataReader dr)
        {
            try
            {
                Car_UseCarApplication obj = new Car_UseCarApplication();
                obj.Id = (dr["Id"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("Id")));
                obj.StartAddress = (dr["StartAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("StartAddress")));
                obj.EndAddress = (dr["EndAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("EndAddress")));
                obj.StartTime = (dr["StartTime"] == System.DBNull.Value ? new DateTime(1900, 1, 1) : dr.GetDateTime(dr.GetOrdinal("StartTime")));
                obj.TotalCount = (dr["TotalCount"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("TotalCount")));
                obj.Remark = (dr["Remark"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("Remark")));
                obj.InstanceState = (dr["InstanceState"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("InstanceState")));
                if (dr["IsComplaint"] != null && dr["IsComplaint"].ToString() != "")
                {
                    if ((dr["IsComplaint"].ToString() == "1") || (dr["IsComplaint"].ToString().ToLower() == "true"))
                    {
                        obj.IsComplaint = true;
                    }
                    else
                    {
                        obj.IsComplaint = false;
                    }
                }
                if (dr["BussinessState"] != null && dr["BussinessState"].ToString() != "")
                {
                    if ((dr["BussinessState"].ToString() == "1") || (dr["BussinessState"].ToString().ToLower() == "true"))
                    {
                        obj.BussinessState = true;
                    }
                    else
                    {
                        obj.BussinessState = false;
                    }
                }
                obj.ComplaintState = (dr["IsComplaint"] == System.DBNull.Value ? 0 : Convert.ToInt32(dr["IsComplaint"]));
                //obj.ApproalUsers = (dr["ApproalUsers"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("ApproalUsers")));
                //obj.NodeCount = (dr["NodeCount"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("NodeCount")));
                obj.UserId = (dr["UserId"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("UserId")));
                obj.DriverName = (dr["DriverName"] == System.DBNull.Value ? String.Empty : dr["DriverName"].ToString());
                obj.CarNo = (dr["CarNo"] == System.DBNull.Value ? String.Empty : dr["CarNo"].ToString());
                obj.Orgz = (dr["DeptName"] == System.DBNull.Value ? String.Empty : dr["OrgzName"].ToString() + "/" + dr["DeptName"].ToString());
                obj.OrgzNo = (dr["OrgzNo"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("OrgzNo")));
                obj.UserName = (dr["UserName"] == System.DBNull.Value ? String.Empty : dr["UserName"].ToString());
                //obj.ExDate = (dr["ExDate"] == System.DBNull.Value ? new DateTime(1900, 1, 1) : dr.GetDateTime(dr.GetOrdinal("ExDate")));
                //obj.Reson = (dr["Reson"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("Reson")));
                //obj.ZcTonnage = (dr["ZcTonnage"] == System.DBNull.Value ? 0M : dr.GetDecimal(dr.GetOrdinal("ZcTonnage")));
                return obj;
            }
            catch (Exception ex)
            {
                throw new Exception("从DataReader中读取数据失败，可能与相关的字段不存在有关！请检查！||" + ex.Message + "||" + ex.Source);
            }
        }

        /// <summary>
        /// 更新派车纪录
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <returns></returns>
        public ReturnModel SaveReturnCar(int bid)
        {
            ReturnModel ent = new ReturnModel();
            string sql = "Proc_ReturnCar";
            SqlParameter[] param = new SqlParameter[]{
                new SqlParameter("@Id",SqlDbType.Int)
            };
            param[0].Value = bid;
            try
            {
                DbHelperSQL.RunProcedure(sql, param);
                ent.SourceId = 1; ent.Message = "还车成功";
                return ent;
            }
            catch (Exception ex)
            {
                ent.SourceId = 0; ent.Message = ex.Message;
                return ent;
            }
        }
        /// <summary>
        /// 从IDataReader中读取数据，组装成实体
        /// </summary>
        /// <param name="dr">数据读取接口</param>
        /// <returns>Car_Accident实体</returns>
        /// <remarks>
        /// </remarks>
        private SendCarTemp BuildObjectFromIDataReader(IDataReader dr)
        {
            try
            {
                SendCarTemp obj = new SendCarTemp();
                obj.Id = (dr["Id"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("Id")));
                obj.Time = (dr["StartTime"] == System.DBNull.Value ? new DateTime(1900, 1, 1) : dr.GetDateTime(dr.GetOrdinal("StartTime")));
                obj.StartAddress = (dr["StartAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("StartAddress")));
                obj.EndAddress = (dr["EndAddress"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("EndAddress")));
                obj.CarNo = (dr["CarNo"] == System.DBNull.Value ? String.Empty : dr.GetString(dr.GetOrdinal("CarNo")));
                obj.TakeCount = (dr["TotalCount"] == System.DBNull.Value ? 0 : dr.GetInt32(dr.GetOrdinal("TotalCount")));
                return obj;
            }
            catch (Exception ex)
            {
                throw new Exception("从DataReader中读取数据失败，可能与相关的字段不存在有关！请检查！||" + ex.Message + "||" + ex.Source);
            }
        }

        /// <summary>
        /// 获取司机业务详细信息
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <param name="type">业务ID</param>
        /// <returns></returns>
        public List<SendCarTemp> GetSCRecord(int bid, int type)
        {
            List<SendCarTemp> list = new List<SendCarTemp>();
            string sql = "SELECT * FROM Vw_SCarRecord WHERE ";
            string str = type == 0 ? "  Driver=" + bid + "" : "  Id=" + bid + "";
            var sl = sql + str + " order by BackTime DESC";
            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sl))
            {
                while (sdr.Read())
                {
                    var item = BuildObjectFromIDataReader(sdr);
                    item.UserName = (sdr["Name"] == System.DBNull.Value ? String.Empty : sdr.GetString(sdr.GetOrdinal("Name")));
                    item.UserPhone = (sdr["Phone"] == System.DBNull.Value ? String.Empty : sdr.GetString(sdr.GetOrdinal("Phone")));
                    item.DriverName = (sdr["DriverName"] == System.DBNull.Value ? String.Empty : sdr.GetString(sdr.GetOrdinal("DriverName")));
                    item.DriverPhone = (sdr["DriverPhone"] == System.DBNull.Value ? String.Empty : sdr.GetString(sdr.GetOrdinal("DriverPhone")));
                    item.CarTypeName = (sdr["CarTypeName"] == System.DBNull.Value ? String.Empty : sdr.GetString(sdr.GetOrdinal("CarTypeName")));
                    var tmp = (sdr["IsBack"] == System.DBNull.Value ? false : sdr.GetBoolean(sdr.GetOrdinal("IsBack")));
                    if (tmp)
                        item.StateName = "已还";
                    else
                        item.StateName = "未还";
                    list.Add(item);
                }
                sdr.Close();
            }
            return list;
        }

        /// <summary>
        /// 获取司机业务详细信息
        /// </summary>
        /// <param name="id">业务ID</param>
        /// <returns></returns>
        public SendCarRecordTemp GetSendCarRecordTemp(int id)
        {
            SendCarRecordTemp ent = new SendCarRecordTemp();
            string sql = "select u.StartTime,s.BackTime,c.CarNo from dbo.SendCarRecord as s,dbo.Car_UseCarApplication as u,dbo.CarInfo as c where s.CarUseNo=u.Id and s.CarNo=c.Id and s.Id=" + id;
            using (SqlDataReader sdr = DbHelperSQL.ExecuteReader(sql))
            {
                while (sdr.Read())
                {
                    ent.CarNo = (sdr["CarNo"] == System.DBNull.Value ? string.Empty : sdr.GetString(sdr.GetOrdinal("CarNo")));
                    ent.StartTime = (sdr["StartTime"] == System.DBNull.Value ? DateTime.MinValue : sdr.GetDateTime(sdr.GetOrdinal("StartTime")));
                    ent.BackTime = (sdr["BackTime"] == System.DBNull.Value ? DateTime.MinValue : sdr.GetDateTime(sdr.GetOrdinal("BackTime")));
                }
                sdr.Close();
            }
            return ent;
        }

    }
}
